-module(my_db_gen).
-behavior(gen_server).

-export([start_link/0,stop/0]).
-export([init/1,terminate/2,handle_call/3,handle_cast/2]).
-export([write/2,delete/1,read/1,match/1]).

%% Exported Client Functions
%% Operation & Maintaienance API

start_link() ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).

stop() ->
    gen_server:cast(?MODULE, stop).

%% Customer Service API
write(Key, Element) ->
    gen_server:call(?MODULE, {write, Key, Element}).

delete(Key) ->
    gen_server:call(?MODULE, {delete, Key}).

read(Key) ->
    gen_server:call(?MODULE, {read, Key}).

match(Element) ->
    gen_server:call(?MODULE, {match, Element}).

%% CallBack Functions
init([]) ->
    {ok, db:new()}.

terminate(_Reason, Db) ->
    db:destroy(Db),
    ok.

handle_cast({stop}, Db) ->
    {stop, normal, Db}.

handle_call({write, Key, Element}, _From, Db) ->
    NewDb = db:write(Key, Element, Db),
    {reply, ok, NewDb};

handle_call({delete, Key}, _From, Db) ->
    NewDb = db:delete(Key, Db),
    {reply, ok, NewDb};

handle_call({read, Key}, _From, Db) ->
    {reply, db:read(Key, Db), Db};

handle_call({match, Element}, _From, Db) ->
    {reply, db:match(Element, Db), Db}.


